﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.Accounts;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Finances.Repository;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using System.Linq;

namespace mozhi.smarterp.Finance.Finances
{
    public class SettlementRepository : EfCoreRepository<FinanceDbContext , Settlement, Guid>, ISettlementRepository
    {
        public SettlementRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<Settlement>> FindAsync(SettlementQuery query)
        {
            var settlements = await DbContext.Set<Settlement>().AsNoTracking().
                 WhereIf(query.Period != 0, x => x.Period == query.Period).
                 WhereIf(query.Closed.HasValue, x => x.Closed == query.Closed.Value)
                .ToListAsync();

            return settlements;
        }

        public async Task<int> GetCountAsync(SettlementQuery query)
        {
            var count = await DbContext.Set<Settlement>().AsNoTracking().
                 WhereIf(query.Period != 0, x => x.Period == query.Period).
                 WhereIf(query.Closed.HasValue, x => x.Closed == query.Closed.Value)
                 .CountAsync();

            return count;
        }

        public async Task<int> GetLastClosePeriod()
        {
           return await DbContext.Set<Settlement>().AsNoTracking().MaxAsync(x => x.Period);
        }
    }
}
